package client;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import javax.websocket.Session;

import com.google.common.collect.Maps;
import com.ruiyun.jvppeteer.core.Puppeteer;
import com.ruiyun.jvppeteer.core.browser.Browser;
import com.ruiyun.jvppeteer.core.page.Page;
import com.ruiyun.jvppeteer.options.LaunchOptions;
import com.ruiyun.jvppeteer.options.LaunchOptionsBuilder;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.StrFormatter;

public class PageContentExample {

    public static void main(String[] args) throws InterruptedException, IOException, ExecutionException {
    	 
        //BrowserFetcher.downloadIfNotExist(null);
        ArrayList<String> arrayList = new ArrayList<>(); 
        LaunchOptions options = new LaunchOptionsBuilder().withArgs(arrayList).withHeadless(false).build();
        arrayList.add("--no-sandbox");
        arrayList.add("--disable-setuid-sandbox");
        
        Map<Integer,Browser> save = Maps.newHashMap();
        Browser browser3 = Puppeteer.launch(options);
        save.put(1, browser3);
        browser3.onDisconnected((s) ->{
        	try {
				Browser browser1 = Puppeteer.launch(false);
				save.put(1, browser1);
				browser1.onDisconnected((s1) ->{
		        	try {
						Browser browser2 = Puppeteer.launch(false);
						save.put(1, browser2);
					} catch (Exception e) { 
						e.printStackTrace();
					} 
		        });
			} catch (Exception e) { 
				e.printStackTrace();
			}
        	
        });
        Browser browser = save.get(1);  
        System.out.println(browser);
    }
    public static void startRoomPage(Page page,Session RoomConn,String RoomId) throws Exception{
    	page.setDefaultNavigationTimeout(0); 
    	page.goTo(StrFormatter.format("https://live.douyin.com/{}", RoomId));
    	page.setRequestInterception(true);
    	page.setCacheEnabled(false);
    	page.exposeFunction("sendRoomMesssage", (a) -> { 
    		System.out.println(a);
    		/*if (a.common.method == "WebcastChatMessage") {
    			ChatMessage data = new ChatMessage();
                const data = {
                    Method: a.common.method,
                    roomId: a.common.roomId,
                    UserId: a.user.id,
                    NickName: a.user.nickname,
                    AvatarThumb: a.user.avatarThumb.urlList[0],
                    Content: a.content
                };
                //console.log(JSON.stringify(data));
                RoomConn.send(JSON.stringify(data))
            } 
            if (a.common.method == "WebcastGiftMessage") {
                const data = {
                    Method: a.common.method,
                    roomId: a.common.roomId,
                    UserId: a.user.id,
                    NickName: a.user.nickname,
                    AvatarThumb: a.user.avatarThumb.urlList[0],
                    GiftId: a.giftId,
                    GiftName: a.gift.name,
                    GiftCount: a.repeatCount
                };
                //console.log(JSON.stringify(data));
                RoomConn.send(JSON.stringify(data))
            }*/
    		return null;
        }); 
    	
    	Path imageFile = Paths.get("src/main/resources/douyin/dd.js");
		 
    	page.onRequest(request -> {  
            if (request.url().toString().indexOf("common-utils-message") != -1) {
               	System.out.println("拦截关键脚本:"+ request.url());
               	Map<String,String> headers = Maps.newHashMap();
               	headers.put("Access-Control-Allow-Origin",  "*"); 
                request.respond(200, headers, "application/javascript", FileUtil.readString(imageFile.toString(), "utf-8"));
    			System.out.println("已替换:"+ request.url());
            } else {
                request.continueRequest();
            }
        });
        page.reload(null);
    }
    
}